package com.ruoyi.record.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.record.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.record.mapper.RecordProfessionalMapper;
import com.ruoyi.record.service.IRecordProfessionalService;
import com.ruoyi.common.core.text.Convert;

/**
 * 职称申报Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-09
 */
@Service
public class RecordProfessionalServiceImpl extends ServiceImpl<RecordProfessionalMapper, RecordProfessional> implements IRecordProfessionalService
{
    @Autowired
    private BasicUserMapper basicUserMapper;

    /**
     * 查询职称申报
     * 
     * @param professionalId 职称申报主键
     * @return 职称申报
     */
    @Override
    public RecordProfessional selectRecordProfessionalByProfessionalId(Long professionalId)
    {
        return baseMapper.selectRecordProfessionalByProfessionalId(professionalId);
    }

    /**
     * 查询职称申报列表
     * 
     * @param recordProfessional 职称申报
     * @return 职称申报
     */
    @Override
    public List<RecordProfessional> selectRecordProfessionalList(RecordProfessional recordProfessional)
    {
        return baseMapper.selectRecordProfessionalList(recordProfessional);
    }

    /**
     * 新增职称申报
     * 
     * @param recordProfessional 职称申报
     * @return 结果
     */
    @Override
    public int insertRecordProfessional(RecordProfessional recordProfessional)
    {
        recordProfessional.setCreateTime(DateUtils.getNowDate());
        int rows = baseMapper.insert(recordProfessional);
        insertRecordProfessionalInfo(recordProfessional);
        return rows;
    }

    /**
     * 修改职称申报
     * 
     * @param recordProfessional 职称申报
     * @return 结果
     */
    @Override
    public int updateRecordProfessional(RecordProfessional recordProfessional)
    {
        recordProfessional.setUpdateTime(DateUtils.getNowDate());
        baseMapper.deleteRecordProfessionalInfo1ByProfessionalId(recordProfessional.getProfessionalId());
        baseMapper.deleteRecordProfessionalInfo2ByProfessionalId(recordProfessional.getProfessionalId());
        baseMapper.deleteRecordProfessionalInfo3ByProfessionalId(recordProfessional.getProfessionalId());
        insertRecordProfessionalInfo(recordProfessional);
        return baseMapper.updateById(recordProfessional);
    }

    /**
     * 批量删除职称申报
     * 
     * @param professionalIds 需要删除的职称申报主键
     * @return 结果
     */
    @Override
    public int deleteRecordProfessionalByProfessionalIds(String professionalIds)
    {
        baseMapper.deleteRecordProfessionalInfo1ByProfessionalIds(Convert.toLongArray(professionalIds));
        baseMapper.deleteRecordProfessionalInfo2ByProfessionalIds(Convert.toLongArray(professionalIds));
        baseMapper.deleteRecordProfessionalInfo3ByProfessionalIds(Convert.toLongArray(professionalIds));
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(professionalIds)));
    }

    /**
     * 删除职称申报信息
     * 
     * @param professionalId 职称申报主键
     * @return 结果
     */
    @Override
    public int deleteRecordProfessionalByProfessionalId(Long professionalId)
    {
        baseMapper.deleteRecordProfessionalInfo1ByProfessionalId(professionalId);
        baseMapper.deleteRecordProfessionalInfo2ByProfessionalId(professionalId);
        baseMapper.deleteRecordProfessionalInfo3ByProfessionalId(professionalId);
        return baseMapper.deleteById(professionalId);
    }

    /**
     * 查询职称申报列表
     *
     * @param recordProfessional 职称申报
     * @return 职称申报
     */
    @Override
    public List<RecordProfessional> selectVerifyProfessionalList(RecordProfessional recordProfessional)
    {
        return baseMapper.selectVerifyProfessionalList(recordProfessional);
    }

    /**
     * 查询职称申报列表
     *
     * @param recordProfessional 职称申报
     * @return 职称申报
     */
    @Override
    public List<RecordProfessional> selectScoreProfessionalList(RecordProfessional recordProfessional)
    {
        return baseMapper.selectScoreProfessionalList(recordProfessional);
    }

    /**
     * 职称申报审批
     * @param recordProfessional
     * @return
     */
    @Override
    public int verifyRecordProfessional(RecordProfessional recordProfessional)
    {
        LambdaUpdateWrapper<RecordProfessional> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(RecordProfessional::getVerifyFlag, recordProfessional.getVerifyFlag());
        updateWrapper.set(RecordProfessional::getVerifyTime, recordProfessional.getVerifyTime());
        updateWrapper.set(RecordProfessional::getVerifyRemark, recordProfessional.getVerifyRemark());
        updateWrapper.eq(RecordProfessional::getProfessionalId, recordProfessional.getProfessionalId());
        return baseMapper.update(null, updateWrapper);
    }

    /**
     * 职称申报审批
     * @param recordProfessional
     * @return
     */
    @Override
    public int scoreRecordProfessional(RecordProfessional recordProfessional)
    {
        LambdaUpdateWrapper<RecordProfessional> updateWrapper = Wrappers.lambdaUpdate();
        if(StringUtils.isNotEmpty(recordProfessional.getScore1())) {
            updateWrapper.set(RecordProfessional::getScore1, recordProfessional.getScore1());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore2())) {
            updateWrapper.set(RecordProfessional::getScore2, recordProfessional.getScore2());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore3())) {
            updateWrapper.set(RecordProfessional::getScore3, recordProfessional.getScore3());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore4())) {
            updateWrapper.set(RecordProfessional::getScore4, recordProfessional.getScore4());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore5())) {
            updateWrapper.set(RecordProfessional::getScore5, recordProfessional.getScore5());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore6())) {
            updateWrapper.set(RecordProfessional::getScore6, recordProfessional.getScore6());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore7())) {
            updateWrapper.set(RecordProfessional::getScore7, recordProfessional.getScore7());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore8())) {
            updateWrapper.set(RecordProfessional::getScore8, recordProfessional.getScore8());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore9())) {
            updateWrapper.set(RecordProfessional::getScore9, recordProfessional.getScore9());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore10())) {
            updateWrapper.set(RecordProfessional::getScore10, recordProfessional.getScore10());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore11())) {
            updateWrapper.set(RecordProfessional::getScore11, recordProfessional.getScore11());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore12())) {
            updateWrapper.set(RecordProfessional::getScore12, recordProfessional.getScore12());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore13())) {
            updateWrapper.set(RecordProfessional::getScore13, recordProfessional.getScore13());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore14())) {
            updateWrapper.set(RecordProfessional::getScore14, recordProfessional.getScore14());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore15())) {
            updateWrapper.set(RecordProfessional::getScore15, recordProfessional.getScore15());
        }
        if(StringUtils.isNotEmpty(recordProfessional.getScore16())) {
            updateWrapper.set(RecordProfessional::getScore16, recordProfessional.getScore16());
        }
        updateWrapper.eq(RecordProfessional::getProfessionalId, recordProfessional.getProfessionalId());
        return baseMapper.update(null, updateWrapper);
    }

    /**
     * 导入档案工资
     *
     * @param professionalList 档案工资列表
     * @return 结果
     */
    @Override
    public String importRecordProfessional(List<RecordProfessional> professionalList, boolean isUpdateSupport)
    {
        if (StringUtils.isNull(professionalList) || professionalList.size() == 0)
        {
            throw new ServiceException("导入职称申报数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordProfessional recordProfessional : professionalList)
        {
            try
            {
                if(StringUtils.isEmpty(recordProfessional.getIdCard())){
                    continue;
                }
                //验证用户是否存在
                BasicUser basicUser = basicUserMapper.selectOne(new LambdaQueryWrapper<BasicUser>().eq(BasicUser::getIdCard, recordProfessional.getIdCard()));
                if(StringUtils.isNull(basicUser)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + recordProfessional.getUserName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(StringUtils.isNotEmpty(recordProfessional.getVerifyTime()) && recordProfessional.getVerifyTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date verifyTime = dateFormat.parse(recordProfessional.getVerifyTime());
                    recordProfessional.setVerifyTime(DateUtils.parseDateToStr("yyyy-MM-dd", verifyTime));
                }

                if(StringUtils.isNotEmpty(recordProfessional.getEducateTime()) && recordProfessional.getEducateTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date educateTime = dateFormat.parse(recordProfessional.getEducateTime());
                    recordProfessional.setEducateTime(DateUtils.parseDateToStr("yyyy-MM-dd", educateTime));
                }

                RecordProfessional info = baseMapper.selectOne(new LambdaQueryWrapper<RecordProfessional>()
                        .eq(RecordProfessional::getCreateBy, recordProfessional.getIdCard())
                        .eq(RecordProfessional::getProfessionalName, recordProfessional.getProfessionalName()));
                if(StringUtils.isNull(info)) {
                    recordProfessional.setVerifyFlag("1");
                    recordProfessional.setCreateBy(basicUser.getIdCard());
                    this.insertRecordProfessional(recordProfessional);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行职称申报信息导入成功");
                }
                else if (isUpdateSupport)
                {
                    recordProfessional.setProfessionalId(info.getProfessionalId());
                    recordProfessional.setVerifyFlag("1");
                    recordProfessional.setUpdateBy(basicUser.getIdCard());
                    this.updateRecordProfessional(recordProfessional);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行职称申报信息更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行职称申报信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行职称申报信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增申请内容信息
     *
     * @param recordProfessional 申请记录对象
     */
    public void insertRecordProfessionalInfo(RecordProfessional recordProfessional)
    {
        List<RecordProfessionalInfo1> professionalInfo1List = recordProfessional.getInfo1List();
        if (StringUtils.isNotNull(professionalInfo1List))
        {
            List<RecordProfessionalInfo1> info1List = new ArrayList<RecordProfessionalInfo1>();
            for (RecordProfessionalInfo1 professionalInfo1 : professionalInfo1List)
            {
                professionalInfo1.setProfessionalId(recordProfessional.getProfessionalId());
                info1List.add(professionalInfo1);
            }
            if (info1List.size() > 0)
            {
                baseMapper.batchRecordProfessionalInfo1(info1List);
            }
        }
        List<RecordProfessionalInfo2> professionalInfo2List = recordProfessional.getInfo2List();
        if (StringUtils.isNotNull(professionalInfo2List))
        {
            List<RecordProfessionalInfo2> info2List = new ArrayList<RecordProfessionalInfo2>();
            for (RecordProfessionalInfo2 professionalInfo2 : professionalInfo2List)
            {
                professionalInfo2.setProfessionalId(recordProfessional.getProfessionalId());
                info2List.add(professionalInfo2);
            }
            if (info2List.size() > 0)
            {
                baseMapper.batchRecordProfessionalInfo2(info2List);
            }
        }
        List<RecordProfessionalInfo3> professionalInfo3List = recordProfessional.getInfo3List();
        if (StringUtils.isNotNull(professionalInfo3List))
        {
            List<RecordProfessionalInfo3> info3List = new ArrayList<RecordProfessionalInfo3>();
            for (RecordProfessionalInfo3 professionalInfo3 : professionalInfo3List)
            {
                professionalInfo3.setProfessionalId(recordProfessional.getProfessionalId());
                info3List.add(professionalInfo3);
            }
            if (info3List.size() > 0)
            {
                baseMapper.batchRecordProfessionalInfo3(info3List);
            }
        }
    }
}
